## Script (Python) "AssessmentExportReport_csv_report.py"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##title=Assessment Explorer (by Models)
##parameters=

#####################################################################
# Product:      KnowledgeEngine (Plone Edition)
#
# File:         AssessmentExportReport_csv_report.py
#
# Copyright:    Copyright (c) 2005, Faulkner Technologies
#
# Author:       Brian Oliver
#
# Description:  A python script to generate a CSV report
#
#####################################################################

#------------------------
#get the request from the context... we will use it to find stuff!
request=context.REQUEST

#get the session from the request
session = request["SESSION"]

#------------------------
#get the sercurity, user provider and assessment storage services
securityService = context.knowledgeengine_securityservice
userProviderService = context.knowledgeengine_userproviderservice
assessmentStorageService = context.knowledgeengine_assessmentstorageservice

#------------------------
#get report parameters from the request
user = userProviderService.getUser(request["AUTHENTICATED_USER"].getId())
now = request['NOW']
wizardState = request['WIZARD_STATE']
assessments = request['ASSESSMENTS']
report = context
model = report.getModel()

#------------------------
#generate the header
header = "Assessment ID,Date Created,Date Modified,Created By,Assessment Name"
if wizardState.getPropertyValue('outputLockStatus'):
    header = header + ",Locked"
for component in [model.getComponent(componentIdentity) for componentIdentity in wizardState.getPropertyValue('exportComponents')]:
    if wizardState.getPropertyValue('outputPath'):
        title = reduce(lambda x,y:'%s : %s' % (x,y), [parent.getTitleOrId() for parent in component.getParents()]) + " : " +  component.getTitleOrId()
    else:
        title = component.getTitleOrId()
    header = header + "," + title
    
#------------------------
#generate the content
content = ""
for assessment in assessments:
    content = content + assessment.getIdentity()
    content = content + ",%s" % (context.toLocalizedTime(assessment.getInstantCreated(), long_format='date_format_short'),)
    content = content + ",%s" % (context.toLocalizedTime(assessment.getInstantModified(), long_format='date_format_short'),)
    
    creator = userProviderService.getUser(assessment.getCreatedBy())
    content = content + ","
    if creator is not None:
        content = content + "'%s'" % (creator.getFullname(),)

    content = content + ",'%s'" % (assessment.getName(),)

    content = content + ","
    if component.isShown(assessment):
        content = content + ",%s" % (assessment.getComponentState(component.getIdentity()).getValue(),)

    content = content + "\n"

#------------------------
return header + "\n" + content

